//
//  MeController.swift
//  我的控制器
//
//  Created by smile on 2019/4/26.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//发布订阅框架
import SwiftEventBus

//导入响应式编程框架
import RxSwift

class MeController: BaseTitleController {
    var dataArray:[Any] = []
    
    var CREATE_SHEET=0
    var COLLECTION_SHEET=10

    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func initViews() {
        super.initViews()
        
        setTitle("我的音乐")
        
        //标题Cell
        tableView.register(UINib(nibName: TitleTableViewCell.NAME, bundle: nil), forCellReuseIdentifier: TitleTableViewCell.NAME)
        
        //按钮Cell
        tableView.register(UINib(nibName: ButtonCell.NAME, bundle: nil), forCellReuseIdentifier: ButtonCell.NAME)
       
        //歌单Cell
        tableView.register(UINib(nibName: TopicCell.NAME, bundle: nil), forCellReuseIdentifier: TopicCell.NAME)
    }
    
    override func initDatas() {
        super.initDatas()
        fetchData()
    }
    
    func fetchData() {
        dataArray.removeAll()
        
        //添加按钮
        dataArray.append(ButtonInfo("LocalMusic", "本地音乐"))
        dataArray.append(ButtonInfo("LocalMusic", "下载管理"))
        dataArray.append(ButtonInfo("LocalMusic", "最近播放"))
        dataArray.append(ButtonInfo("LocalMusic", "我的电台"))
        dataArray.append(ButtonInfo("LocalMusic", "我的收藏"))
        dataArray.append(ButtonInfo("LocalMusic", "Sati 空间"))
        
        dataArray.append(Title("创建的歌单", true,CREATE_SHEET))
        
        let createSheetsApi=Api.shared
            .createSheets(PreferenceUtil.userId()!)
        
        let collectSheets=Api.shared
            .collectSheets(PreferenceUtil.userId()!)
        
        //使用RxSwift
        //实现两个请求并发访问网络
        //两个都请求成功后回调
        Observable.zip(createSheetsApi, collectSheets) { (createSheetsApi, collectSheets) -> (ListResponse<Sheet>?,ListResponse<Sheet>?)  in
            //将两个信号合并成一个信号
            //并压缩成一个元组返回
            //两个信号均成功的才会返回
                return (createSheetsApi,collectSheets)
            }
            
            //在子线程中执行
            .observeOn(MainScheduler.instance)
            
            //这里不能使用subscribeOnSuccess
            //因为他是专门用户处理网络请求的
            //我们在扩展的时候写死了
            .subscribe(onNext: { (createSheetsResponse, collectSheetsResponse) in
                //处理数据

                //创建的歌单
                self.dataArray=self.dataArray+(createSheetsResponse?.data ?? [])

                self.dataArray.append(Title("收藏的歌单", false,self.COLLECTION_SHEET))

                //收藏的歌单
                self.dataArray=self.dataArray+(collectSheetsResponse?.data ?? [])

                self.tableView.reloadData()

            }, onError: nil, onCompleted: nil, onDisposed: nil)
            .disposed(by: disposeBag)
        
        
        //这里普通的回调方式
        //请求是线性执行的
        //获取创建的歌单
//        Api.shared
//            .createSheets(PreferenceUtil.userId()!)
//            .subscribeOnSuccess { (data) in
//                self.dataArray=self.dataArray+(data.data ?? [])
//
//                //获取收藏的歌单
//                Api.shared
//                    .collectSheets(PreferenceUtil.userId()!)
//                    .subscribeOnSuccess({ (data) in
//                        self.dataArray.append(Title("收藏的歌单", true,self.COLLECTION_SHEET))
//
//                        self.dataArray=self.dataArray+(data.data ?? [])
//
//                        self.tableView.reloadData()
//                    })
//        }
    }
    
    
    override func initListeners() {
        super.initListeners()
        
        //监听创建了歌单
        SwiftEventBus.onMainThread(self, name: ON_SHEET_CREATED) { result in
            //重新获取数据
            self.fetchData()
        }
    }
    
    /// <#Description#>
    ///
    /// - Parameter indexPath: <#indexPath description#>
    func processOnMoreClick(_ indexPath:IndexPath) {
        let data=dataArray[indexPath.row] as! Title
        if CREATE_SHEET==data.tag {
            //创建的歌单标题点击
            print("MeController processOnMoreClick create collection")
            
            CreateSheetController.start(navigationController!)
        }else{
            //收藏的歌单标题点击
            print("MeController processOnMoreClick collection sheet")
            
            ToastUtil.short("收藏的歌单分组点击！")
        }
        
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension MeController: UITableViewDataSource,UITableViewDelegate {
    // MARK:- TableView数据源
    /// 返回有多个条目
    /// 和CollectionView差不多
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - section: <#section description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    /// 返回当前位置的Cell
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    /// - Returns: <#return value description#>
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = dataArray[indexPath.row]
    
        let type=typeForItemAtData(data)

        //根据Cell类型创建Cell
        switch type {
        case .title:
            var cell=tableView.dequeueReusableCell(withIdentifier: TitleTableViewCell.NAME, for: indexPath) as! TitleTableViewCell
            
            //绑定数据
            cell.bindData((data as! Title))
            
            //更多点击回调方法
            cell.onMoreClick={
                print("MeController onMoreClick:\(indexPath)")
                self.processOnMoreClick(indexPath)
            }
            
            return cell
        case .sheet:
            var cell=tableView.dequeueReusableCell(withIdentifier: TopicCell.NAME, for: indexPath) as! TopicCell
            
            //绑定数据
            cell.bindData(data as! Sheet)
            
            return cell
        default:
            var cell=tableView.dequeueReusableCell(withIdentifier: ButtonCell.NAME, for: indexPath) as! ButtonCell
            
            cell.tag=indexPath.row
            
            //绑定数据
            cell.bindData(data as! ButtonInfo)
            
            return cell
        }
        
        
    }
    
    /// Item点击事件
    ///
    /// - Parameters:
    ///   - tableView: <#tableView description#>
    ///   - indexPath: <#indexPath description#>
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = dataArray[indexPath.row]
        
        let type=typeForItemAtData(data)
        
        switch type {
        case .title:
            //标题点击不处理
            //所以直接返回
           break
        case .sheet:
            //歌单点击
            SheetDetailController.start(navigationController!, (data as! Sheet).id)
        default:
            //按钮点击
            if indexPath.row==0{
                //本地音乐
                print("MeController local music")
                LocalMusicController.start(navigationController!)
            }else if indexPath.row==1{
                //下载管理
                print("MeController download manager")
                DownloadController.start(navigationController!)
            }
        }
       
    }
    
    /// 获取列表类型
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    func typeForItemAtData(_ data:Any) -> CellType {
        if data is Title {
            return .title
        }else if data is Sheet {
            return .sheet
        }
        
        return .button
    }
    
    /// Cell类型；这是一个枚举
    enum CellType {
        case title
        case button
        case sheet
    }
}
